<template>
	<statusBarVue title="添加卡片" :isShowBar="true" :isShowLeft="true" :isMyBgi="true" />
	<view class="bankcards-add-page" :style="pageHaveBarStyle">
		<uni-forms ref="form" :model="formData" :rules="rules" label-position="top" class="form">
			<view class="chunk">
				<uni-forms-item label="卡号" name="account" required>
					<uni-easyinput type="number" v-model="formData.account" placeholder="请输入" primaryColor="#22A366"
						:disabled="cardId" @keyboardheightchange="handleOnFocusKeyboardHeight" />
				</uni-forms-item>
				<uni-forms-item label="开户行" name="bank" required>
					<uni-easyinput v-model="formData.bank" placeholder="请输入" primaryColor="#22A366"
						:disabled="cardId" />
				</uni-forms-item>
			</view>
			<view class="chunk">
				<uni-forms-item label="开户姓名" name="name" required>
					<uni-easyinput v-model="formData.name" placeholder="请输入" primaryColor="#22A366"
						:disabled="cardId" />
				</uni-forms-item>
				<uni-forms-item label="联系电话" name="phone" required>
					<uni-easyinput type="tel" v-model="formData.phone" placeholder="请输入" primaryColor="#22A366"
						:disabled="cardId" />
				</uni-forms-item>
			</view>
		</uni-forms>

		<button v-if="cardId === undefined" style="color:#ffffff;backgroundColor:#22A366;"
			@click="handleAddDocument">保存</button>
	</view>
</template>

<script>
	import statusBarVue from '@/components/statusBar.vue'

	import {
		postAddBankcards
	} from '@/utils/api.js';

	import {
		publics
	} from '@/mixins/publics.js';

	export default {
		mixins: [publics],
		data() {
			return {
				cardId: undefined,
				formData: {},
				rules: {
					// name:
					name: {
						// 校验 name 不能为空
						rules: [{
							required: true,
							errorMessage: '开户姓名不能为空',
						}]
					},
					// account:
					account: {
						// 校验 account 不能为空
						rules: [{
								required: true,
								errorMessage: '卡号不能为空',
							},
							{
								validateFunction: (rule, value, data, callback) => {
									const phonePattern = /^1\d{10}$/;
									// debugger
									if (!(this.validateCardNumber(value))) {
										callback('卡号格式错误')
									}
									return true
								}
							}
						]
					},
					// bank:
					bank: {
						// 校验 bank 不能为空
						rules: [{
							required: true,
							errorMessage: '开户行不能为空',
						}]
					},
					// phone:
					phone: {
						// 校验 phone 不能为空
						rules: [{
								required: true,
								errorMessage: '联系电话不能为空',
							},
							{
								validateFunction: function(rule, value, data, callback) {
									const phonePattern = /^1\d{10}$/;
									// debugger
									if (!(phonePattern.test(value))) {
										callback('手机号码格式错误')
									}
									return true
								}
							}
						]
					}
				}
			}
		},
		components: {
			statusBarVue
		},
		onLoad(options) {
			if (options.str) {
				this.cardId = JSON.parse(options.str)?.id;
				this.formData = JSON.parse(options.str)
			}
		},
		methods: {
			// 添加证书
			handleAddDocument() {
				this.$refs.form.validate((err, formData) => {
					if (!err) {
						let {
							account,
							bank,
							name,
							phone
						} = {
							...formData
						};
						let postBankCardData = {
							account: account.replace(/\s/g, ''),
							bank,
							name,
							phone
						};

						postAddBankcards(postBankCardData).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: '银行卡添加成功！',
									success: function(res) {
										uni.navigateBack(); // 返回上一页
									}
								});
							}
						})
					}
				});


			},

			//银行卡号校验（Luhn 算法）
			validateCardNumber(cardNumber) {
				// 移除空格并检查卡号是否为数字
				cardNumber = cardNumber.replace(/\s+/g, '');
				if (!/^\d+$/.test(cardNumber)) {
					return false;
				}

				let sum = 0;
				let shouldDouble = false;

				// 从右到左遍历卡号的每一位数字
				for (let i = cardNumber.length - 1; i >= 0; i--) {
					let digit = parseInt(cardNumber.charAt(i));

					// 如果应该乘 2
					if (shouldDouble) {
						digit *= 2;
						if (digit > 9) {
							digit -= 9; // 如果乘积大于9，减去9
						}
					}

					sum += digit;
					shouldDouble = !shouldDouble; // 每次反转是否乘2

				}

				// 如果总和能被10整除，卡号有效
				return sum % 10 === 0;
			}
		}
	}
</script>

<style lang="scss">
	.bankcards-add-page {
		margin: auto;
		position: fixed;
		left: 0;
		right: 0;
		background-color: #F2F3F7;
		padding: 10px 2.66vw;
		box-sizing: border-box;
		z-index: 99;
	}
</style>